import {PlusOutlined} from '@ant-design/icons';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import type {ActionType, ProColumns} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {Button, Divider, message, Modal} from 'antd';
import type {SorterResult} from 'antd/es/table/interface';
import React, {useRef, useState} from 'react';
import type {
  AuthPermission,
  AuthPermissionAddItem,
  AuthPermissionEditItem,
  AuthPermissionTableListItem,
} from './data';
import {
  addAdminAccess,
  editPermission,
  getPermission,
  queryAdminAccessList,
  removePermission,
} from './service';
import AddFrom from './components/AuthPermissionAddForm';
import AuthPermissionEditForm from './components/AuthPermissionEditForm';

const TableList: React.FC<{}> = () => {
  const [sorter, setSorter] = useState<string>('');
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [editModalVisible, handleEditModalVisible] = useState<boolean>(false);
  const [detailItemId, setDetailItemId] = useState<string | null>(null);

  const actionRef = useRef<ActionType>();

  async function handleAdd(fields: AuthPermissionAddItem) {
    const hide = message.loading('正在添加');
    try {
      await addAdminAccess(fields);
      hide();
      message.success('添加成功');
      handleAddModalVisible(false);
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      handleAddModalVisible(false);
      return false;
    }
  }

  async function handleEdit(fields: AuthPermissionEditItem) {
    const hide = message.loading('正在修改');
    try {
      // @ts-ignore
      await editPermission(fields);
      hide();
      message.success('修改成功');
      handleEditModalVisible(false);
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('修改失败请重试！');
      handleEditModalVisible(false);
      return false;
    }
  }

  async function handleRemove(fields: AuthPermission) {
    const hide = message.loading('正在删除');
    try {
      await removePermission(fields);
      hide();
      message.success('删除成功');
      handleEditModalVisible(false);
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      handleEditModalVisible(false);
      return false;
    }
  }

  const columns: ProColumns<AuthPermissionTableListItem>[] = [
    {
      title: '权限名称',
      dataIndex: 'name',
    },
    {
      title: '权限识别码',
      dataIndex: 'code',
      hideInSearch: true,
    },
    {
      title: '权限描述',
      dataIndex: 'desc',
      hideInSearch: true,
    },
    {
      title: '操作',
      hideInSearch: true,
      render: (_, record) => {
        const onClickEdit = async () => {
          handleEditModalVisible(true);
          setDetailItemId(record.id);
        };

        const onClickRemove = () => {
          const {id, name} = record;
          Modal.confirm({
            title: `删除权限字典`,
            content: (
                <>
                  <Divider/>
                  <p>确认要删除权限字典</p>
                  <span style={{fontWeight: 'bolder'}}>{name}</span>&nbsp;&nbsp;?
                </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove({id});
            },
          });
        };

        return (
            <div>
              <a onClick={onClickEdit}>修改</a>
              <Divider type="vertical"/>
              <a onClick={onClickRemove}>删除</a>
            </div>
        );
      },
    },
  ];

  return (
      <PageHeaderWrapper>
        <ProTable<AuthPermissionTableListItem>
            headerTitle="权限列表"
            actionRef={actionRef}
            rowKey="id"
            scroll={{x: true}}
            onChange={(_, _filter, _sorter) => {
              const sorterResult = _sorter as SorterResult<AuthPermissionTableListItem>;
              if (sorterResult.field) {
                setSorter(`${sorterResult.field}_${sorterResult.order}`);
              }
            }}
            params={{
              sorter,
            }}
            toolBarRender={() => [
              <Button type="primary" onClick={() => handleAddModalVisible(true)}>
                <PlusOutlined/> 添加
              </Button>,
            ]}
            tableAlertRender={() => false}
            request={(params = {}) => {
              return queryAdminAccessList(params);
            }}
            columns={columns}
            rowSelection={false}
        />
        {editModalVisible && detailItemId && (
            <AuthPermissionEditForm
                ruleId={detailItemId}
                request={async (id) => {
                  const data = await getPermission({id});
                  if (data) {
                    return {success: true, data};
                  }
                  return {success: false, data: null};
                }}
                modalVisible={editModalVisible}
                onSubmit={(value: AuthPermissionEditItem) => handleEdit(value)}
                onCancel={() => handleEditModalVisible(false)}
            />
        )}
        <AddFrom
            modalVisible={addModalVisible}
            onSubmit={(value) => handleAdd(value)}
            onCancel={() => handleAddModalVisible(false)}
        />
      </PageHeaderWrapper>
  );
};

export default TableList;
